<template>
  <div :class="{'mobile-order-info': showMobilePage}" class="order-info-container">
    <div v-if="stepThreeData && stepThreeData.selectCost && stepThreeData.selectCost.length" class="order-info-top">
      <div class="cost-item-list">
        <div
          v-for="(item) in selectCost"
          :key="item.costId"
          :class="{'is-selected': showCostList.includes(item.costId)}"
          class="cost-item"
          @click="setSelect(item.costId)">
          {{ item.name }}
        </div>
      </div>
      <div v-if="isCanInvite" class="invite-btn-list">
        <el-tooltip content="刷新">
          <img :src="resetFilterIcon" class="img" alt="" @click="refreshOrderList">
        </el-tooltip>
        <el-button type="primary" size="small" class="invite-btn" @click="handleWrite">填写订单</el-button>
        <el-button type="info" size="small" class="invite-user-btn" @click="handleInvite">邀请他人填写</el-button>
      </div>
    </div>
    <div v-if="ordersAndCost.orders && ordersAndCost.orders.length" class="cost-info-table">
      <Title title="订单信息" style="margin-bottom: 16px;" />
      <div v-if="stepOneData.costBelong ===0 || stepOneData.costBelong===5">
        <dataDisplay :data-list="dataList" style="margin: 0 0 10px 0" />
      </div>
      <u-table
        :data="ordersAndCost.orders"
        :height="ordersAndCost.orders.length >= 30?600:''"
        :row-height="49"
        :border="false"
        use-virtual
        class="fb-table"
        header-cell-class-name="order-data-header-cell">
        <u-table-column
          v-for="(item) in tableInfoSetting[stepOneData.costBelong.toString()]"
          v-bind="item.props"
          :fixed="item.type === 'operate' ? 'right' : false"
          :key="item.key">
          <template slot-scope="scope">
            <OrderTableRender :table-info="item" :table-data="scope.row" @onOperate="onOperate(scope.row)" />
          </template>
        </u-table-column>
      </u-table>
    </div>
    <div v-if="ordersAndCost.costs && ordersAndCost.costs.length">
      <Title title="成本信息" style="margin-bottom: 16px;" />
      <u-table
        :data="ordersAndCost.costs"
        :height="ordersAndCost.costs.length >= 30?600:''"
        :row-height="49"
        :border="false"
        class="fb-table"
        use-virtual
        header-cell-class-name="order-data-header-cell"
      >
        <u-table-column label="成本编号" align="left" min-width="180">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.costNum" is-can-click @handelClick="toCostDetail(scope.row.orderCostItemId)" />
          </template>
        </u-table-column>
        <u-table-column label="成本项" align="left" min-width="130">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.costName || scope.row.costItemName" />
          </template>
        </u-table-column>
        <u-table-column label="含税成本(元)" align="right" min-width="120">
          <template slot-scope="scope">
            <div v-if="scope.row.taxCost || scope.row.taxCost === 0">{{ scope.row.taxCost/100 | moneyFilter }}</div>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column label="供应商" align="left" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.supplierName" />
          </template>
        </u-table-column>
        <u-table-column label="说明" align="left" min-width="190">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.costDescription" />
          </template>
        </u-table-column>
        <u-table-column label="成本来源" align="left" min-width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.costBelong | costBelongFilter }}</div>
          </template>
        </u-table-column>
        <u-table-column label="成本类型" align="left" min-width="90">
          <template slot-scope="scope">
            <div>{{ scope.row.costType | costTypeFilter }}</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="审批状态" width="80">
          <template slot-scope="scope">
            <StatusText :color="['#FD8546','#31CC9C', 'FF4E5F'][scope.row.approvalStatus]" :text="scope.row.approvalStatus | costApprovalStatus" />
          </template>
        </u-table-column>
        <u-table-column label="创建时间" align="left" min-width="150">
          <template slot-scope="scope">
            <div>{{ scope.row.createDate | format('YYYY/MM/DD HH:mm') }}</div>
          </template>
        </u-table-column>
        <u-table-column label="创建人" align="left" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.creator || '--' }}
          </template>
        </u-table-column>
        <u-table-column v-if="isCanInvite" label="操作" fixed="right" align="left" min-width="100">
          <template slot-scope="scope">
            <div class="button-text" @click="onOperate(scope.row, false)">删除</div>
          </template>
        </u-table-column>
      </u-table>
    </div>
    <EmptyPlaceholder
      v-if="!ordersAndCost.costs.length && !ordersAndCost.orders.length"
      :empty-img="emptyDefaultImg"
      image-size="120px" />

    <OrderSelectDialog
      ref="SelectOrderSelectDialogRef"
      :visible.sync="showOrderSelect"
      :step-one-data="stepOneData"
      :settle-id="settleId"
      @refreshOrderList="refreshOrderList"
    />
    <Dialog
      ref="inviteDialogRef"
      :btn1="'确认提交'"
      :btn2="'取消'"
      :requestDept="true"
      :inviteUrl="inviteUrl"
      :isInvite="stepOneData.isInvite"
      summary="邀请他人填写订单"
      tip="接收人请选择订单/成本负责人，或复制邀请链接给相关人员"
      @handelOK="inviteConfirm" />
  </div>
</template>
<script>
// components
import { setting } from '@/components/SupplierComponent/module/orderTableInfo.js';
import OrderTableRender from '@/components/SupplierComponent/module/orderTableRender';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import Dialog from '@/components/CreateOrder/orderDetail/dialog';
import OrderSelectDialog from '@/views/supplier/components/OrderSelectDialog';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
// api
import { inviteOthers, deleteSettleOrder } from '@/api/supplier';
// filters
import { encryption } from '@/utils';
import { moneyFilter } from '@/filters/number';
import { format } from '@/filters/date';
import math from '@/utils/math';
import { costBelongFilter, costTypeFilter, costApprovalStatus } from '@/filters/status';
import { mapState } from 'vuex';
// img
import incomeAmount from '@/assets/chargeOffDetail/incomeAmount.png';
import transactionNumber from '@/assets/chargeOffDetail/transactionNumber.png';
import supplierIcon from '@/assets/mengli/mengliorder/supplier.png';
import resetFilterIcon from '@/assets/setting/resetFilter.png';

import emptyDefaultImg from '@/assets/empty-table-data.png';
export default {
  name: 'SettlementOrderInfo',
  components: {
    OrderTableRender, Title, EmptyPlaceholder, OrderSelectDialog, Dialog,
    dataDisplay
  },

  inject: {
    getIsExamineing: { default: null },
    getIsExamined: { default: null },
    freshDetail: { default: null },
    operateData: { default: { auth: [] }}
  },
  filters: { moneyFilter, format, costBelongFilter, costTypeFilter, costApprovalStatus },
  props: {
    settleId: {
      type: Number | String,
      default: null
    },
    stepThreeData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    stepOneData: {
      // costBelong, supplierId, isInvite
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      emptyDefaultImg, resetFilterIcon,
      currentPage: 1,
      pageSize: 20,
      showCostList: [],
      showOrderSelect: false,
      costAndOrderLoading: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isCanInvite() {
      return this.stepOneData.isInvite && !this.isExamineing && !this.isExamined && !this.operateData.auth.includes(10);
    },
    tableInfoSetting() {
      const arr = [];
      const costBelong = this.stepOneData.costBelong;
      if (this.stepOneData.isInvite) {
        arr.push({ key: 'submitUser', props: { label: '提交人', minWidth: '120' }});
        arr.push({ key: 'submitTime', props: { label: '提交时间', minWidth: '170' }});
      }
      if (this.isCanInvite) {
        arr.push({ key: 'delete', type: 'operate', typeName: '删除', props: { label: '操作', minWidth: '100' }});
      }
      const temp = _.cloneDeep(setting);
      temp[costBelong.toString()] = [...temp[costBelong.toString()], ...arr];
      let insertIndex;
      if (costBelong.toString() === '0') {
        insertIndex = 6;
      } else if (costBelong.toString() === '5') {
        insertIndex = 5;
      }
      if (temp[costBelong.toString()].length) {
        temp[costBelong.toString()].splice(insertIndex || 1, 0, {
          key: 'grossProfit', type: 'price', props: { label: '毛利(元)', minWidth: '100', align: 'right' }
        });
      }
      return temp;
    },
    selectCost() {
      const selectCost = this.stepThreeData.selectCost;
      const isInvite = this.stepThreeData.isInvite;
      let ans = _.cloneDeep(selectCost);
      if (!selectCost) return [];
      const isFromDetail = selectCost.some(i => Object.hasOwnProperty.call(i, 'costList'));
      if (isFromDetail) {
        ans = ans.map(i => {
          if (!i.costList) i.costList = [];
          const temp = {
            costId: i.id,
            name: i.name,
            orderIds: [],
            orderCostItemIds: []
          };
          i.costList.forEach(orderItem => {
            if (!orderItem._isCost) {
              temp.orderIds.push(orderItem);
            } else {
              temp.orderCostItemIds.push(orderItem);
            }
          });
          return temp;
        });
      } else if (!isInvite) {
        ans = ans.filter(i => i.orderIds.length || i.orderCostItemIds.length);
      }
      return ans;
    },
    ordersAndCost() {
      const showCostList = this.showCostList;
      let orders = [];
      let costs = [];
      this.selectCost.forEach(i => {
        if (showCostList.includes(i.costId)) {
          orders = orders.concat(i.orderIds);
          costs = costs.concat(i.orderCostItemIds);
        }
      });
      return { orders, costs };
    },
    dataList() {
      const { orders } = this.ordersAndCost;
      let taxAmountTotal = null;
      let orderCostTotal = null;
      let grossProfitTotal = null;
      let profit = null;
      _.uniqBy(orders, 'orderId').forEach(i => {
        if (i.taxAmount || i.taxAmount === 0) {
          if (taxAmountTotal === null) taxAmountTotal = 0;
          taxAmountTotal = math.add(taxAmountTotal, i.taxAmount);
        }
        if (i.orderCost || i.taxAmount === 0) {
          if (orderCostTotal === null) orderCostTotal = 0;
          orderCostTotal = math.add(orderCostTotal, i.orderCost);
        }
        if (i.grossProfit || i.grossProfit === 0) {
          if (grossProfitTotal === null) grossProfitTotal = 0;
          grossProfitTotal = math.add(grossProfitTotal, i.grossProfit);
        }
      });
      if (taxAmountTotal) taxAmountTotal = math.divide(taxAmountTotal, 100);
      if (orderCostTotal) orderCostTotal = math.divide(orderCostTotal, 100);
      if (grossProfitTotal) grossProfitTotal = math.divide(grossProfitTotal, 100);
      if (taxAmountTotal) { // taxAmountTotal不能为0
        // 毛利率 = (含税金额 - 总成本) / 含税金额
        profit = math.divide(math.subtract(taxAmountTotal, orderCostTotal), taxAmountTotal);
        profit = math.multiply(profit, 100).toFixed(2);
      }
      return [
        { label: '含税金额', icon: incomeAmount, data: taxAmountTotal },
        { label: '总成本', icon: transactionNumber, data: orderCostTotal },
        { label: '总毛利', icon: supplierIcon, data: grossProfitTotal },
        { label: '毛利率', icon: supplierIcon, data: profit, unit: '%' }
      ];
    },
    inviteUrl() {
      const inviteCode = encryption(this.settleId);
      return `${location.origin}/#/businessPage/supplierDetail?settleId=${this.settleId}&id=${this.stepOneData.supplierId}&isSettle=true&isInvite=${inviteCode}`;
    },
    isExamineing() {
      if (this.getIsExamineing) return this.getIsExamineing();
      return false;
    },
    isExamined() {
      if (this.getIsExamined) return this.getIsExamined();
      return false;
    }
  },

  mounted() {
    if (this.selectCost) {
      this.showCostList = this.selectCost.map(i => i.costId);
    }
  },
  methods: {
    setSelect(costId) {
      if (this.showCostList.includes(costId)) {
        this.showCostList = this.showCostList.filter(i => i !== costId);
      } else {
        this.showCostList.push(costId);
      }
    },

    handleWrite() {
      if (this.$refs.SelectOrderSelectDialogRef) this.$refs.SelectOrderSelectDialogRef.openDrawer();
    },
    handleInvite() {
      this.$refs.inviteDialogRef.showDialog({ defaultMsg: '有新结算单需要您协作完成' });
    },

    refreshOrderList() {
      if (this.freshDetail) this.freshDetail();
    },
    onOperate(row, isOrder = true) {
      this.$confirm(`是否确定删除该${isOrder ? '订单' : '成本'}`, '', {
        iconClass: 'del-icon',
        customClass: 'del-message del-message-cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning'
      }).then(() => {
        const params = {
          settleId: this.settleId,
          orderCostItemId: row.orderCostItemId
        };
        deleteSettleOrder(params).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.refreshOrderList();
          }
        });
      }).catch(() => {
        return false;
      });
    },
    inviteConfirm(data) {
      data.settleId = this.settleId;
      inviteOthers(data).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
        }
      }).catch(err => console.error(err.message));
    },
    toCostDetail(id) {
      const routeUrl = this.$router.resolve({
        name: 'costDetail',
        params: { id }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.order-info-top {
  display: flex;
  align-items: flex-start;
}
.order-info-container {
  .invite-btn-list {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    .img {
      width: 14px;
      height: 14px;
      cursor: pointer;
    }
  }
}
.cost-item-list {
  display: flex;
  flex-wrap: wrap;
  flex: 1;
  .cost-item {
    border: 1px solid #f5f5f5;
    margin-bottom: 20px;
    background: #f5f5f5;
    margin-right: 16px;
    border-radius: 4px;
    font-size:14px;
    font-weight:400;
    color:#192452;
    height: 30px;
    line-height: 30px;
    padding: 0 12px;
    cursor: pointer;
    &.is-selected {
      border-color: #406EFF;
      background: #eff3ff;
      color:#406EFF;
    }
  }
}
.cost-info-table {
  margin-bottom: 32px;
}
.invite-btn {
  border: 1px solid #406eff;
  color: #406EFF;
  background-color: #fff;
  padding: 7px 12px;
  margin-left: 12px;
}
.invite-user-btn {
  border: 1px solid #DDDDDD;
  color: #333333;
  background-color: #fff;
  padding: 7px 12px;
  margin-left: 12px;
}
.mobile-order-info {
  .order-info-top {
    display: block;
    .cost-item-list {
      flex-wrap: nowrap;
      overflow-x: auto;
      .cost-item {
        white-space: nowrap;
      }
    }
    .invite-btn-list {
      justify-content: flex-end;
    }
  }
}
</style>
